package com.example.braden.answergame.common.view;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.example.braden.answergame.R;

/**
 * Created by braden on 2018/3/26.
 */

public class BackDialog extends Dialog {
    @BindView(R.id.tv_back_content) TextView tvBackContent;
    @BindView(R.id.btn_cancle) Button btnCancle;
    @BindView(R.id.btn_back) Button btnBack;
    private static Context mComtext;
    private static BackDialog instance;

    public BackDialog(@NonNull Context context) {
        super(context);
        mComtext = context;
        initView();
    }

    public BackDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        mComtext = context;
        initView();
    }

    public static BackDialog getInstance(Context context) {
        if (instance == null || !mComtext.equals(context)) {
            synchronized (BackDialog.class) {
                if (instance == null || !mComtext.equals(context)) {
                    instance = new BackDialog(context, R.style.dialog);
                }
            }
        }
        mComtext = context;
        return instance;
    }

    private void initView() {
        View view1 = LayoutInflater.from(mComtext).inflate(R.layout.back_dialog, null);
        setContentView(view1);
        ButterKnife.bind(this);
        setCanceledOnTouchOutside(false);
        btnCancle.setOnClickListener(view -> dismiss());

        //setCancelable(false);
    }

    private ConfirmCallback callback;

    public BackDialog setConfirmCallback(ConfirmCallback callback) {
        this.callback = callback;
        return instance;
    }

    public interface ConfirmCallback {
        void confirm(Dialog view);
    }

    public void showDialog() {
        if (isShowing()) {
            dismiss();
        }
        btnBack.setOnClickListener(view -> {
            if (callback != null) {
                callback.confirm(this);
            } else {
                dismiss();
            }
        });
        show();
    }

    public void showDialog(String content, View.OnClickListener clickListener) {
        tvBackContent.setText(content);
        btnBack.setOnClickListener(clickListener);
        show();
    }

    public void showDialog(String content, View.OnClickListener clickListener, String leftStr,
            String rightStr) {
        btnCancle.setText(leftStr);
        btnBack.setText(rightStr);
        btnBack.setOnClickListener(clickListener);
        show();
    }

    public void closeDialog() {
        dismiss();
    }
}
